package com.example.demo.util;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HaleyHa
 * @date 2021/12/10 19：18
 * @description 二维码 工具类
 *
 * **/
@Component
public class QRCodeUtil {
    //日志
//    private static final Logger logger = LoggerFactory.getLogger(QRCodeUtils.class);

    //二维码颜色
    private static final int BLACK = 0xFF000000;
    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;
    //二维码宽
    private static final int width = 200;
    //二维码高
    private static final int height = 200;
    //二维码生成格式
    private static final String imageType = "png";

    /**
     * 生成二维码
     * @param text    二维码内容
     */
    public static String zxingCodeCreate(String text) throws Exception{
        String URL = "http://47.92.204.3:8080/test?id="+text;
        HashMap map = new HashMap();
        //EncodeHintType枚举类 纠错程度（使得其精度增加）
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //字符编码
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        //二维码边距
        map.put(EncodeHintType.MARGIN,1);

        //生成二维码
        BitMatrix encode = new MultiFormatWriter().encode(URL,BarcodeFormat.QR_CODE,width,height);
        int codeWidth = encode.getWidth();
        int codeHeight = encode.getHeight();
        BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);// BufferedImage.TYPE_INT_RGB 颜色参数
        for (int i = 0; i < codeWidth; i++) {
            for (int j = 0; j < codeHeight; j++) {
                //4、循环将二维码内容定入图片
                image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
            }
        }
        String fileName = "QRCode"+text+"."+imageType;
        File file = new File("/root/xpj_images/",fileName);
        ImageIO.write(image,"jpg",file);

        return imageToString(image);

    }

    //把image对象转换成Base64方法
    public static String imageToString(BufferedImage image) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image,imageType,os);
        return Base64.encodeBase64String(os.toByteArray());
    }

}

